package br.com.zeroutrocou.dao.jdo;

import javax.jdo.PersistenceManager;

import br.com.zeroutrocou.dao.IBaseDAO;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;


public abstract class BaseDAO<T> implements IBaseDAO<T>{
	
	private PersistenceManager persistenceManager;
	
	public PersistenceManager getPersistenceManager() {
		return persistenceManager;
	}

	public void setPersistenceManager(PersistenceManager persistenceManager) {
		this.persistenceManager = persistenceManager;
	}

	public T pesquisar(Class<T> classe, long chave) {
		Key key = KeyFactory.createKey(classe.getSimpleName(), chave);
        return persistenceManager.getObjectById(classe, key);
	}
	
	public void apagar(T t){
		try {
			getPersistenceManager().currentTransaction().begin();
			getPersistenceManager().deletePersistent(t);
			getPersistenceManager().currentTransaction().commit();
		} finally {
			if (getPersistenceManager().currentTransaction().isActive()) { 
				getPersistenceManager().currentTransaction().rollback(); 
		    } 
		}
	}
	
	public void gravar(T t) {

		try {
			getPersistenceManager().currentTransaction().begin();
			getPersistenceManager().makePersistent(t);
			getPersistenceManager().currentTransaction().commit();
		} finally {
			if (getPersistenceManager().currentTransaction().isActive()) { 
				getPersistenceManager().currentTransaction().rollback(); 
		    } 
		}
	}
}
